<?php

App::uses('AppModel', 'Model');

class Event extends AppModel {
    
    public $order = 'Event.start DESC';
    
    public $hasAndBelongsToMany = array ('Member', 'Guest');
    
    public $hasMany = array ('EventsMember', 'EventsGuest', 'Chronicle', 'EventsRepertoireMember', 'EventsRepertoireGuest',
        'EventChild' => array(
            'className' => 'Event',
            'foreignKey' => false,
            'finderQuery' => 'SELECT * FROM events EventChild WHERE EventChild.parent_id={$__cakeID__$}'
        )
    );
    public $belongsTo = array(
        'EventParent' => array(
            'className' => 'Event',
            'foreignKey' => 'parent_id'
        ),
        'EventConductor' => array(
            'className' => 'Member',
            'foreignKey' => 'conductor_id'
        )
    );
    
    public function afterFind($results=array(), $primary=false) {
        $results = parent::afterFind($results, $primary);
        
        if ($primary) {
            
            foreach ($results as $k=>$result) {
                if (! empty($result['EventsRepertoireMember'])) {
                    foreach ($result['EventsRepertoireMember'] as $v) {
                        $repertoireId = $v['repertoire_id'];
                        if (! $results[$k]['EventsRepertoire'][$repertoireId]) {
                            $results[$k]['EventsRepertoire'][$repertoireId] = array();
                        }
                        $results[$k]['EventsRepertoire'][$repertoireId]['members'][] = $v;
                    }
                }
                if (! empty($result['EventsRepertoireGuest'])) {
                    foreach ($result['EventsRepertoireGuest'] as $v) {
                        $repertoireId = $v['repertoire_id'];
                        if (! $results[$k]['EventsRepertoire'][$repertoireId]) {
                            $results[$k]['EventsRepertoire'][$repertoireId] = array(
                                'members' => array(),
                                'guests'  => array()
                            );
                        }
                        $results[$k]['EventsRepertoire'][$repertoireId]['guests'][] = $v;
                    }
                }
            }
        }
        
        return $results;
    }
    
    public function refactorData($data) {
        // refactor Members and functions
        if (! empty($data['EventsMember']['member_id'])) {
            $tmp = array();
            foreach ($data['EventsMember']['member_id'] as $k=>$member_id) {
                $tmp[$member_id] = array(
                    'member_id'   => $member_id
                );
            }
            $data['EventsMember'] = $tmp;
        }

        // refactor Guests
        if (! empty($data['EventsGuest']['guest_id'])) {
            $tmp = array();
            foreach ($data['EventsGuest']['guest_id'] as $guest_id) {
                $tmp[$guest_id] = array('guest_id' => $guest_id);
            }
            $data['EventsGuest'] = $tmp;
        }
        
        // refactor Event Repertoire
        if (! empty($data['EventRepertoire']['repertoire_id'])) {
            $tmp1 = $tmp2 = array();
            foreach($data['EventRepertoire']['repertoire_id'] as $k=>$id) {
                $repertoireId = $id;
                
                $members = $data['EventsRepertoireMember'][$k];
                foreach ($members['id'] as $kk=>$id) {
                    $memberId = $members['member_id'][$kk];
                    $tmp1["{$repertoireId}_{$memberId}"] = array(
                        'id'            => $id,
                        'repertoire_id' => $repertoireId,
                        'member_id'     => $memberId
                    );
                }
                
                $guests  = $data['EventsRepertoireGuest'][$k];
                foreach ($guests['id'] as $kk=>$id) {
                    $guestId = $guests['guest_id'][$kk];
                    $tmp2["{$repertoireId}_{$guestId}"] = array(
                        'id'            => $id,
                        'repertoire_id' => $repertoireId,
                        'guest_id'     => $guestId
                    );
                }
            }
            $data['EventsRepertoireMember'] = array_values($tmp1);
            $data['EventsRepertoireGuest'] = array_values($tmp2);
        }
        
        //refactor chronicles
        if (! empty($data['Chronicle'])) {
            $tmp = array();
            
            foreach ($data['Chronicle']['title'] as $k=>$title) {
                $file = $data['Chronicle']['newFile'][$k];
                if (! $file['error']) {
                    $filename = $file['name'];
                } else {
                    $filename = $data['Chronicle']['file'][$k];
                }
                
                $tmp[] = array(
                    'position' => $k,
                    'title'    => $title,
                    'file'     => $filename,
                    'newFile'  => $file
                );
            }
            $data['Chronicle'] = $tmp;
        }
        
        return $data;
    }
    
    public function deleteRelationsData($id=null) {
        if (! $id) {
            $id = $this->id;
        }
        
        if ($id) {
            $this->EventsMember->deleteAll(array('event_id' => $id));
            $this->EventsGuest->deleteAll(array('event_id' => $id));
            $this->Chronicle->deleteAll(array('event_id' => $id));
            $this->EventsRepertoireMember->deleteAll(array('event_id' => $id));
            $this->EventsRepertoireGuest->deleteAll(array('event_id' => $id));
        }
    }
    
    public function removeOldFiles() {
        $id = $this->id;
        if ($id) {
            $data = $this->findById($id);
            $files = Set::extract('Chronicle.{n}.file', $data);
            $dirname = WWW_ROOT . implode(DS, array('img', 'chronicles', $id));
            @removeAllFilesExcept($dirname, $files);
        }
    }
    
    public function groupByVoice(&$data=null) {
        if (! $data) {
            $data = &$this->data;   
        }
        
        $data['MembersByVoice'] = array();
        foreach ($data['Member'] as $member) {
            $voice = $member['voice'];
            if (empty($data['MembersByVoice'][$voice])) {
                $data['MembersByVoice'][$voice] = array();
            }
            
            $data['MembersByVoice'][$voice][] = $member;
        }
    }
}
